package com.wuyou.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.wuyou.domain.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


@RestController
@RequestMapping("/file")
public class FileController {

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
    @Value("${oss.http}")
    private String http;
    @Value("${oss.endpoint}")
    private String endpoint;
    // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
    @Value("${oss.accessKeyId}")
    private String accessKeyId;
    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;

    // 填写Bucket名称，例如examplebucket。
    @Value("${oss.bucketName}")
    private String bucketName;
    // 填写Object完整路径
    @Value("${oss.imageDir}")
    private String imageDir;

    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public Result upload(@RequestParam("myImage") MultipartFile myImage) {
        logger.info("myImage = {}",myImage);
        String objectName = imageDir + myImage.getOriginalFilename();//图片路径
        // 创建OSSClient实例。
        OSS ossClient = null;
        try {
            ossClient = new OSSClientBuilder().build(http + endpoint, accessKeyId, accessKeySecret);
            ossClient.putObject(bucketName, objectName, myImage.getInputStream());
        } catch (Exception e) {
            logger.error("oss upload exception = ",e);
            return Result.ERROR(e.getMessage());
        } finally {
            if (ossClient != null)   ossClient.shutdown();
        }
        String concat = http.concat(bucketName)
                .concat(".")
                .concat(endpoint)
                .concat("/")
                .concat(objectName);
        return Result.OK().setData(concat);
    }
}
